package cn.didi.feidi.androidorder.util;

import android.app.ActivityManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by king on 2017/8/2.
 */
public class AppUtil {

    private static final String TAG = "AppUtil";

    /**
     * 检测当的网络（WLAN、3G/2G）状态
     *
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检测格式是否为手机号
     *
     * @param phoneNum
     * @return true 纯11 位手机号码
     */
    public static boolean checkPhone(String phoneNum) {

        if (TextUtils.isEmpty(phoneNum)) {
            return false;
        }

        phoneNum = phoneNum.trim();
        if (phoneNum.length() != 11) {
            return false;
        }

        if (!TextUtils.isDigitsOnly(phoneNum)) {
            return false;
        }

        //定义需要匹配的正则表达式的规则
        String REGEX_MOBILE_SIMPLE = "[1][358]\\d{9}";
        //把正则表达式的规则编译成模板
        Pattern pattern = Pattern.compile(REGEX_MOBILE_SIMPLE);
        //把需要匹配的字符给模板匹配，获得匹配器
        Matcher matcher = pattern.matcher(phoneNum);

        return matcher.find();

    }

    /**
     * 检测格式是否为电子邮箱
     *
     * @param email
     * @return true 纯11 位手机号码
     */
    public static boolean checkmail(String email) {

        if (TextUtils.isEmpty(email)) {
            return false;
        }

        email = email.trim();

        //定义需要匹配的正则表达式的规则
        String REGEX_MOBILE_SIMPLE = "^[a-z0-9]+([._\\\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$";
        //把正则表达式的规则编译成模板
        Pattern pattern = Pattern.compile(REGEX_MOBILE_SIMPLE);
        //把需要匹配的字符给模板匹配，获得匹配器
        Matcher matcher = pattern.matcher(email);

        return matcher.find();

    }

    /**
     * 由数字和字母组成，并且要同时含有数字和字母，且长度要在6-16位之间
     *
     * @param value
     * @return true 密码正确
     */
    public static boolean checkPassword(String value) {

        if (TextUtils.isEmpty(value)) return false;

//        if (string.length() < 6 || string.length() > 16) return false;

        String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";

        return value.matches(regex);
    }

    /**
     * 由数字和字母组成，首位为字母，并且要同时含有数字和字母，且长度要在6-20位之间
     *
     * @param value
     * @return true 飞滴号
     */
    public static boolean checkFeidiAccount(String value) {

        if (TextUtils.isEmpty(value)) return false;

        String regex = "^[a-zA-Z]{1}[-_a-zA-Z0-9]{5,19}$";

        return value.matches(regex);
    }

    /**
     * 唯一的设备ID： GSM手机的 IMEI 和 CDMA手机的 MEID. Return null if device ID is not
     * 取得手机IMEI
     *
     * @param context
     * @return
     */
//    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    public static String getDeviceId(Context context) {
        // 获取telephony系统服务，用于取得SIM卡和网络相关信息
        TelephonyManager mTelephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);

        String mDeviceId = mTelephonyManager.getDeviceId();// String
        return mDeviceId;
    }

    //判断WiFi是否打开
    public static boolean isWiFi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    /**
     * 把long型时间变成字符串型
     *
     * @param time
     * @param format
     * @return
     */
    public static String dateTransferString(long time, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = new Date(time);
        return simpleDateFormat.format(date);
    }

    public static int dp2px(@NonNull Context context, int dp) {

//        Log.d(TAG, "dp2px:densityDpi   " + context.getResources().getDisplayMetrics().densityDpi);
//        Log.d(TAG, "dp2px:xdpi    " + context.getResources().getDisplayMetrics().xdpi);
//        Log.d(TAG, "dp2px: ydpi  " + context.getResources().getDisplayMetrics().ydpi);
//        Log.d(TAG, "dp2px: " + context.getResources().getDisplayMetrics().density);
        Log.d(TAG, "dp2px: " + context.getResources().getDisplayMetrics().density * dp);
        return (int) (context.getResources().getDisplayMetrics().density * dp);
    }

//    格式化long类型的时间
    public static String formatTimeInMillis(long timeInMillis) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(timeInMillis);
        Date date = cal.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String fmt = dateFormat.format(date);

        return fmt;
    }

    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
                BACKGROUND=400 EMPTY=500 FOREGROUND=100
                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                 */
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }
}
